<template>
  <div class="container">
    <el-button
      size="small"
      type="primary"
      @click="addSchool"
      style="margin-bottom: 20px; float: right"
      >添加学校<i class="el-icon-circle-plus-outline"></i
    ></el-button>
    <el-table
      v-loading="isLoading"
      :data="tableData"
      border
      :row-style="{ height: '100px' }"
      style="width: 100%"
      :header-cell-style="{ background: '#FAFAFA', color: '#333333' }"
      :span-method="objectSpanMethod"
    >
      <el-table-column
        prop="shName"
        label="学校名称"
        width="width"
        align="center"
      >
      </el-table-column>

      <el-table-column align="center" label="logo" width="width">
        <template slot-scope="{ row }">
          <img
            style="width: 20%; height: 20%"
            v-if="row.shRemark"
            :src="$store.state.user.BASE_URL + row.shRemark"
            alt=""
          />
        </template>
      </el-table-column>
      <el-table-column align="center" label="学校二维码" width="width">
        <template slot-scope="{ row }">
          <img
            style="width: 40%; height: 40%"
            v-if="row.schoolCode"
            :src="$store.state.user.BASE_URL + row.schoolCode"
            alt=""
            @click="previewCode(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="inviteCode"
        label="邀请码"
        width="width"
        align="center"
      >
      </el-table-column>
      <el-table-column align="center" label="禁用状态" width="width">
        <template slot-scope="{ row }">
          <el-switch
            @change="changeIsDisable(row)"
            v-model="row.enableStatus"
            active-value="0"
            :inactive-value="'1'"
            active-color="#13ce66"
          >
          </el-switch>
        </template>
      </el-table-column>
        <el-table-column align="center" label="全功能状态" width="width">
        <template slot-scope="{ row }">
          <el-switch
            @change="changeIsDisables(row)"
            v-model="row.shSource"
            active-value="0"
            :inactive-value="'1'"
            active-color="#13ce66"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="userName"
        label="管理员名称"
        width="width"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="userPhone"
        label="手机号"
        width="width"
        align="center"
      >
        <template slot-scope="scope">
          {{
          scope.row.userPhone ?
            scope.row.userPhone.replace(
              scope.row.userPhone.substring(3, 7),
              "****"
            ):""
          }} </template
        >>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="{ row }">
          <el-button plain type="danger" size="small" @click="del($event, row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="{ row }">
          <el-button plain size="small" @click="add(row)">添加</el-button>
          <el-button plain type="primary" size="small" @click="compile(row)"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="form.shId ? '修改学校' : '添加学校'"
      :visible.sync="dialogFormVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="学校名称:" prop="shName">
          <el-input
            placeholder="请输入学校名称"
            v-model="form.shName"
            style="width: 70%"
          ></el-input>
        </el-form-item>
        <el-form-item label="管理员姓名:" prop="userName" v-if="!form.shId">
          <el-input
            placeholder="请输入管理员姓名"
            v-model="form.userName"
            style="width: 70%"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="userPhone" v-if="!form.shId">
          <el-input
            placeholder="请输入手机号"
            v-model="form.userPhone"
            style="width: 70%"
          ></el-input>
        </el-form-item>
        <el-form-item label="学校地区:" prop="areaValue" v-if="!form.shId">
          <el-cascader
            :props="{}"
            placeholder="请选择地区"
            v-model="form.areaValue"
            :options="areaSource"
            @change="handleChangeArea"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="自动生成年级:" prop="schoolType" v-if="!form.shId">
          <el-cascader
            v-model="form.schoolType"
            placeholder="请选择是否自动生成"
            :options="options"
            :props="{ expandTrigger: 'hover' }"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="学校logo:" prop="shRemark" style="width: 70%">
          <el-upload
            class="upload-demo"
            drag
            v-loading="loading"
            :on-success="picUpload"
            :before-upload="beforeUpload"
            :action='$env.BASE_URL+"/homework/zhty/public/import_file"'
            multiple
            :headers="{
              'access-token': $store.state.user.TOKEN,
            }"
          >
            <div v-if="!form.shRemark">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </div>
            <img
              style="
                width: auto;
                height: auto;
                max-height: 100%;
                max-width: 100%;
              "
              v-if="form.shRemark"
              :src="$store.state.user.BASE_URL + form.shRemark"
              alt=""
            />
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，建议不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button
          size="small"
          :loading="submitLoading"
          type="primary"
          @click="save"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      title="学校二维码"
      :visible.sync="dialogFormVisible1"
      width="700px"
      style="height: 700px"
    >
      <div style="display: flex; justify-content: center; align-items: center">
        <img
          style="width: 400px; height: 400px"
          :src="$store.state.user.BASE_URL + chckedImage"
          alt=""
        />
      </div>
      <div slot="footer" class="dialog-footer"></div>
    </el-dialog>
    <el-dialog
      title="添加管理员"
      :visible.sync="dialogFormVisible2"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
        <el-form-item label="管理员姓名:" prop="userName">
          <el-input v-model="form.userName" style="width: 70%"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="userPhone">
          <el-input v-model="form.userPhone" style="width: 70%"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible2 = false"
          >取 消</el-button
        >
        <el-button
          size="small"
          :loading="submitLoading2"
          type="primary"
          @click="addsave"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <pagination-page @size="changeSize" @page="changePage" :total="total" />
  </div>
</template>

<script>
import {
  schoolList,
  addSchool,
  addSchoolAccount,
  delSchoolAccount,
  schoolMessage,
  changeDisable,
  updateSchoolSource
} from "@/api/school/school/index.js";
import Decrypt from "@/utils/Decrypt";
import encryption from "@/utils/encryption";
import { AreaList } from "@/api/school/regionalManager";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      options: [
        {
          value: "shi",
          label: "是",
          children: [
            {
              value: "1",
              label: "小学",
            },
            {
              value: "2",
              label: "初中",
            },
            {
              value: "3",
              label: "高中",
            },
          ],
        },
        {
          value: "0",
          label: "否",
        },
      ],
      total: -1,
      loading: false,
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      dialogFormVisible2: false,
      dialogFormVisible1: false,
      dialogFormVisible: false,
      tableData: [],
      areaSource: [],
      form: {
        shName: "",
        userPhone: "",
        userName: "",
        shRemark: "",
        shId: "",
        areaValue: [],
        schoolType: [],
      },
      rules: {
        shName: [
          {
            required: true,
            message: "请输入学校名字",
          },
        ],
        userName: [
          {
            required: true,
            message: "请输入管理员名字",
          },
        ],
        shRemark: [
          {
            required: true,
            message: "请选择学校logo",
          },
        ],
        areaValue: [
          {
            required: true,
            message: "请选择地区",
          },
        ],
        schoolType: [
          {
            required: true,
            message: "请选择是否自动生成年级",
          },
        ],
        userPhone: [
          {
            required: true,
            message: "请输入手机号",
          },
          {
            min: 7,
            max: 11,
            message: "长度必须在7-11个之间",
            trigger: "blur", // 触发校验的时机是失去焦点
          },
        ],
      },

      isLoading: false,
      chckedImage: "",
      submitLoading: false,
      submitLoading2: false,
    };
  },
  computed: {
    aa() {
      return this.form.schoolType[1] == undefined ? 0 : this.form.schoolType[1];
    },
  },
  watch: {},
  created() {
    this.getSchoolList();
    this.getAreaList();
  },
  mounted() {},
  methods: {
    handleChange(value) {
    },
    handleChangeArea(e) {
    },
    getAreaList() {
      AreaList({}).then((response) => {
        if (response.code == 200) {
          let arr = response.result;
          let arr1 = [];
          arr.map((value, index, arry) => {
            arr1.push({
              label: value.regionName,
              value: value.regionCode,
              parentRegionCode: value.parentRegionCode,
              children: value.childList.map((item) => ({
                ...item,
                label: item.regionName,
                value: item.regionCode,
                children: item.childList.map((v) => ({
                  ...v,
                  label: v.regionName,
                  value: v.regionCode,
                })),
              })),
            });
          });
          this.areaSource = arr1;
        }
      });
    },
    mergeComon(id, rowIndex) {
      // 合并单元格
      var idName = this.tableData[rowIndex][id];
      if (rowIndex > 0) {
        // eslint-disable-next-line eqeqeq
        if (this.tableData[rowIndex][id] != this.tableData[rowIndex - 1][id]) {
          var i = rowIndex;
          var num = 0;
          while (i < this.tableData.length) {
            if (this.tableData[i][id] === idName) {
              i++;
              num++;
            } else {
              i = this.tableData.length;
            }
          }
          return {
            rowspan: num,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 1,
          };
        }
      } else {
        var i = rowIndex;
        var num = 0;
        while (i < this.tableData.length) {
          if (this.tableData[i][id] === idName) {
            i++;
            num++;
          } else {
            i = this.tableData.length;
          }
        }
        return {
          rowspan: num,
          colspan: 1,
        };
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      switch (columnIndex) {
        case 0:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
          break;
        case 3:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
          break;
        case 4:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
          break;
        case 1:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
          break;
        case 2:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
          break;
        case 9:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
            case 5:
          return this.mergeComon("shName", rowIndex);
          // eslint-disable-next-line no-unreachable
          break;
      }
    },
    previewCode(row) {
      this.dialogFormVisible1 = true;
      this.chckedImage = row.schoolCode;
    },
    beforeUpload(file) {
      this.loading = true;
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const types = ["jpeg", "jpg", "png"];
      if (!types.includes(fileSuffix)) {
        this.$message.error(`文件只能是 ${types.join()} 格式!`);
        this.loading = false;
      }
      return types.includes(fileSuffix);
    },
    changeIsDisable(row) {
      changeDisable({ schoolId: row.shId }).then((response) => {
        if (response.code == 200) {
          this.$message.success(response.result);
          this.getSchoolList();
        } else {
          this.$message.error(response.message);
        }
      });
    },
    changeIsDisables(row) {
      updateSchoolSource({ shId: row.shId }).then((response) => {
        if (response.code == 200) {
          this.$message.success(response.message);
          this.getSchoolList();
        } else {
          this.$message.error(response.message);
        }
      });
    },
    picUpload(e) {
      if (e.code === 200) {
        this.form.shRemark = e.result.pic;
      } else if (e.code === 401) {
        this.$router.replace("/");
        this.$message.error("您的身份信息已过期，请重新登录");
        sessionStorage.removeItem("userInfo");
        sessionStorage.removeItem("token");
        this.$store.commit("user/SET_TOKEN", "");
      } else {
        this.$message.error(e.message);
      }
      this.$refs.ruleForm.validate(() => {});
      this.loading = false;
    },
    //获取学校列表
    getSchoolList() {
      let data = {
        ...this.page,
        userId: this.$store.state.user.USER_INFO.id,
      };
      this.isLoading = true;
      schoolList(data).then((res) => {
        if (res.code == 200) {
          this.tableData = res.result.list.map((item) => ({
            ...item,
            userPhone: item.userPhone ? Decrypt(item.userPhone) : "",
          }));
          this.total = res.result.total;
          // this.tableData = res.result.list
          this.isLoading = false;
        }
      });
    },
    //添加学校
    addSchool() {
      this.dialogFormVisible = true;
      (this.form = {
        shId: null,
        shName: "",
        phone: "",
        shRemark: "",
        userId: this.$store.state.user.USER_INFO.id,
        areaValue: [],
        schoolType: [],
      }),
        this.$nextTick(() => {
          this.$refs.ruleForm.clearValidate();
        });
    },
    //添加学校管理员
    add(row) {
      (this.form = {
        shId: null,
        shName: "",
        phone: "",
        shRemark: "",
        userId: this.$store.state.user.USER_INFO.id,
      }),
        (this.dialogFormVisible2 = true);
      this.form.shId = row.shId;
      this.$nextTick(() => {
        this.$refs.ruleForm.clearValidate();
      });
    },
    //编辑学校
    compile(row) {
      this.dialogFormVisible = true;
      this.$set(this.form, "shName", { ...row }.shName);
      this.$set(this.form, "userPhone", { ...row }.userPhone);
      this.$set(this.form, "userName", { ...row }.userName);
      this.$set(this.form, "shRemark", { ...row }.shRemark);
      this.$set(this.form, "shId", { ...row }.shId);
      this.$set(this.form, "userId", this.$store.state.user.USER_INFO.id);
    },
    save() {
      // 对所有表单项进行统一校验
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          let data = {
            ...this.form,
            schoolType:
              this.form.schoolType[1] == undefined
                ? 0
                : this.form.schoolType[1],
            userPhone: encryption(this.form.userPhone),
            districtCode: this.form.areaValue[0],
            cityCode: this.form.areaValue[1],
            countyCode: this.form.areaValue[2],
          };
          addSchool(data).then((res) => {
            this.submitLoading = false;
            if (res.code == 200) {
              this.$message.success(res.message);
              this.dialogFormVisible = false;
              this.getSchoolList();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    addsave() {
      // 对所有表单项进行统一校验
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          this.submitLoading2 = true;
          let data = {
            userPhone: encryption(this.form.userPhone),
            userName: this.form.userName,
            shId: this.form.shId,
          };
          addSchoolAccount(data).then((res) => {
            this.submitLoading2 = false;
            if (res.code == 200) {
              this.$message.success(res.message);
              this.dialogFormVisible2 = false;
              this.getSchoolList();
            } else {
              this.$message.error(res.message);
            }
          });
        } else {
          return false;
        }
      });
    },
    del(evt, row) {
      let target = evt.target;
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (target.nodeName == "SPAN") {
            target = evt.target.parentNode;
          }
          target.blur();
          let data = {
            shId: row.shId,
            userId: row.userId,
          };

          delSchoolAccount(data).then((res) => {
            if (res.code == 200) {
              this.getSchoolList(
                this.tableData.length === 1 && this.page.pageSize > 1
                  ? this.page.pageSize - 1
                  : this.page.pageSize
              );
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          if (target.nodeName == "SPAN") {
            target = evt.target.parentNode;
          }
          target.blur();
          this.$message({
            type: "info",
            message: "取消删除",
          });
        });
    },
    //确定保存
    send() {
      this.$confirm("是否确定发送?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "发送成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消发送",
          });
        });
    },
    changeSize(size) {
      this.page.pageSize = size;
      this.getSchoolList();
    },
    changePage(page) {
      this.page.pageNum = page;
      this.getSchoolList();
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: white !important;
}
::v-deep .el-table__row.statistics-warning-row {
  background: #f5f7fa;
}
::v-deep .el-upload-list__item {
  display: none;
}
</style>
